public without sharing class OpportunityMonthFollowHandler {
    
/*
	当新建/编辑业务机会月度跟进情况、意向产品月度跟进情况时，按照年份+月份跟当前日期进行对比，标记距离当前日期最近的跟进情况为最近一次跟进情况。

*/

    //before 的时判断 当前更新的 是否要新  
    public static void lastFollowup(List<OpportunityMonthFollow__c> list_new,Map<Id,OpportunityMonthFollow__c> oldMap ){

    	Set<Id> oppset  = new Set<Id>();

      for(OpportunityMonthFollow__c omf : list_new){

        
        OpportunityMonthFollow__c old = oldMap == null ? null : oldMap.get(omf.Id );
        if(omf.Opportunity__c != null &&  (old == null || omf.LastFollowup__c == old.LastFollowup__c)  )oppset.add(omf.Opportunity__c);
      }
      if( oppset.size() == 0)return;

      Map<Id,List<OpportunityMonthFollow__c>> omfMap = new Map<Id,List<OpportunityMonthFollow__c>>();
      for(OpportunityMonthFollow__c omf : [select Year__c , Month__c , Opportunity__c ,LastFollowup__c 
        from OpportunityMonthFollow__c where Opportunity__c in: oppset ]){
        
        List<OpportunityMonthFollow__c> tmp = omfMap.containsKey(omf.Opportunity__c) ? omfMap.get(omf.Opportunity__c) : new List<OpportunityMonthFollow__c>(); 
        tmp.add(omf);
        omfMap.put(omf.Opportunity__c,tmp );
      }
      Set<Id>newomfset = new Set<Id>();
      List<OpportunityMonthFollow__c> omfList = new List<OpportunityMonthFollow__c>();
       Set<Id> omfset = new Set<Id>();

         System.debug('lastFollowup==>'+omfMap);
      for(Id oppId : omfMap.keySet()){
        
        //OpportunityMonthFollow__c omf = getLastestOmf(omfMap.get(oppId));
        OpportunityMonthFollow__c tmp = null;
        for(OpportunityMonthFollow__c omf : omfMap.get(oppId)){
          if(tmp == null) tmp = omf;
          if(omf.Year__c == null ||omf.Month__c == null )continue;
            if(omf.LastFollowup__c == true )omfset.add(omf.Id);
                tmp =(omf.Year__c.compareTo(tmp.Year__c) > 0  || omf.Year__c.compareTo(tmp.Year__c) < 0) ? ( omf.Year__c.compareTo(tmp.Year__c)  > 0 ? omf : tmp  ) :(getMonth(omf.Month__c) > getMonth(tmp.Month__c)  ? omf : tmp ) ;
          
        }
            //如果当前最新已经标记 则跳过 
        if(tmp != null && tmp.LastFollowup__c == true ){
                newomfset.add(tmp.Id);
                continue;
            }
        omfList.add(new OpportunityMonthFollow__c(Id=tmp.Id,LastFollowup__c = true));
        newomfset.add(tmp.Id);

      }
         System.debug(newomfset);

        System.debug(omfset);
      for(Id  omfId : omfset ){
        if( newomfset.size() > 0 &&  !newomfset.contains(omfId))omfList.add(new OpportunityMonthFollow__c(Id =omfId,LastFollowup__c = false));

      }
      if(omfList.size() > 0) update omfList;


    } 

    private static Integer getMonth(String m){
        if(m == null) return null;
        try{
           return  m.length() > 1 ? Integer.valueOf( m.substring(0,m.length() -1)): Integer.valueOf(m);
        }catch(Exception e ){
            return null;
        }
    }

    
}